using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Data.SqlClient;
using System.Net.Mail;
using System.Text.RegularExpressions;

/// <summary>
/// Summary description for GeneralFunction
/// </summary>
public class GeneralFunction
{
    #region GetBaseSiteURL
    /// <summary>
    /// Gets the BaseSiteUrl
    /// </summary>
    public static string BaseSiteUrl
    {
        get
        {
            HttpContext context = HttpContext.Current;
            string baseUrl = context.Request.Url.Scheme + "://" + context.Request.Url.Authority + context.Request.ApplicationPath.TrimEnd('/') + '/';
            return baseUrl;
        }
    }

    #endregion

    #region SplitText
    /// <summary>
    /// Split the text into array
    /// </summary>
    /// <param name="textToSplit">String to be splited</param>
    /// <param name="splitter">Spearator character</param>
    /// <returns></returns>
    public static string[] SplitText(string textToSplit, string splitter)
    {
        if (textToSplit.IndexOf(splitter) != -1 && splitter != string.Empty)
        {
            int count = 0;
            string temp = textToSplit;
            int count2 = splitter.Length;
            while (temp.IndexOf(splitter) != -1)
            {
                int seq = temp.IndexOf(splitter);
                int top = seq + count2;
                temp = temp.Remove(0, top);
                count++;
            }
            string[] splittedText = new string[count + 1];
            int i = 0;
            while (textToSplit.IndexOf(splitter) != -1)
            {
                int seq = textToSplit.IndexOf(splitter);
                splittedText[i] = textToSplit.Substring(0, seq);
                textToSplit = textToSplit.Remove(0, (seq + count2));
                i++;
            }
            splittedText[count] = textToSplit;
            return splittedText;
        }
        return new string[] { textToSplit };
    }
    
    #endregion

    #region RemoveDuplicateRowsFromDataTable
    /// <summary>
    /// Removes the duplicate record based on supplied column
    /// </summary>
    /// <param name="dTable">Provide Datatable which contains duplicate record</param>
    /// <param name="colName">Removes duplicate record based on the column name</param>
    /// <returns></returns>
    public static DataTable RemoveDuplicateRows(DataTable dTable, string colName)
    {
        Hashtable hTable = new Hashtable();
        ArrayList duplicateList = new ArrayList();

        foreach (DataRow drow in dTable.Rows)
        {
            if (hTable.Contains(drow[colName]))
                duplicateList.Add(drow);
            else
                hTable.Add(drow[colName], string.Empty);
        }

        foreach (DataRow dRow in duplicateList)
            dTable.Rows.Remove(dRow);

        return dTable;
    }

    #endregion

    #region ExecuteDataTable
    /// <summary>
    /// Executes the DataTable
    /// </summary>
    /// <param name="storedProcedureName">Stored Procedure Name</param>
    /// <param name="arrParam">SqlParameter</param>
    /// <returns></returns>
    //public static DataTable ExecuteDataTable(string storedProcedureName, params SqlParameter[] arrParam)
    //{
    //    DataTable dt = new DataTable();

    //    // Open the connection 
    //    using (SqlConnection cnn = DB.NewSqlConnection())
    //    {
    //        cnn.Open();

    //        // Define the command 
    //        using (SqlCommand cmd = new SqlCommand())
    //        {
    //            cmd.Connection = cnn;
    //            cmd.CommandType = CommandType.StoredProcedure;
    //            cmd.CommandText = storedProcedureName;

    //            // Handle the parameters 
    //            if (arrParam != null)
    //            {
    //                foreach (SqlParameter param in arrParam)
    //                    cmd.Parameters.Add(param);
    //            }

    //            // Define the data adapter and fill the dataset 
    //            using (SqlDataAdapter da = new SqlDataAdapter(cmd))
    //            {
    //                da.Fill(dt);
    //            }
    //        }
    //    }
    //    return dt;
    //}

    #endregion

    #region ExecuteDataTable
    /// <summary>
    /// Executes the DataTable
    /// </summary>
    /// <param name="storedProcedureName">Stored Procedure Name</param>
    /// <param name="arrParam">SqlParameter</param>
    /// <returns></returns>
    public static DataTable ExecuteDataTable(string storedProcedureName, params SqlParameter[] arrParam)
    {
        DataTable dt = new DataTable();
        //using (SqlConnection conn = DB.NewSqlConnection())
        //{
        //    try
        //    {
        //        conn.Open();
        //        if (arrParam != null)
        //        {
        //            SqlDataReader reader = DB.ExecuteStoredProcReader(storedProcedureName, arrParam, conn);
        //            dt.Load(reader);
        //        }
        //        else
        //        {
        //            SqlDataReader reader = DB.SPGetRS(storedProcedureName, conn);
        //            dt.Load(reader);
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //    }
        //}
        return dt;
    }

    #endregion

    #region GetDetailByValue
    /// <summary>
    /// Gets details by supplied criteria
    /// </summary>
    /// <param name="storedProcedureName">Stored Procedure Name</param>
    /// <param name="ht">Hashtable containing criteria</param>
    /// <returns></returns>

    //public static DataTable GetDetailByValue(string storedProcedureName, Hashtable ht)
    //{
    //    DataTable dt = new DataTable();
    //    using (SqlConnection conn = DB.NewSqlConnection())
    //    {
    //        using (SqlCommand cmd = new SqlCommand(storedProcedureName, conn))
    //        {
    //            cmd.CommandType = CommandType.StoredProcedure;
    //            IDictionaryEnumerator e = ht.GetEnumerator();
    //            while (e.MoveNext())
    //            {
    //                cmd.Parameters.AddWithValue(e.Key.ToString(), e.Value.ToString());
    //            }
    //            using (SqlDataAdapter da = new SqlDataAdapter(cmd))
    //            {
    //                da.Fill(dt);
    //            }
    //            return dt;
    //        }
    //    }
    //}
    #endregion

    #region InsertRecord
    /// <summary>
    /// Insert the record in the database
    /// </summary>
    /// <param name="storedProcedureName">Stored Procedure Name</param>
    /// <param name="ht">Hashtable of data to be inserted</param>
    /// <returns></returns>
    public static int InsertRecord(string storedProcedureName, Hashtable ht)
    {
        int intResult = 0;
        //using (SqlConnection conn = DB.NewSqlConnection())
        //{
        //    using (SqlCommand cmd = new SqlCommand(storedProcedureName, conn))
        //    {
        //        cmd.CommandType = CommandType.StoredProcedure;
        //        if (ht.Count > 0)
        //        {
        //            IDictionaryEnumerator e = ht.GetEnumerator();
        //            while (e.MoveNext())
        //            {
        //                cmd.Parameters.AddWithValue(e.Key.ToString(), e.Value.ToString());
        //            }
        //        }
        //        cmd.Parameters.Add(new SqlParameter("@ReturnVal", SqlDbType.Int));
        //        cmd.Parameters["@ReturnVal"].Direction = ParameterDirection.Output;
        //        conn.Open();
        //        cmd.ExecuteScalar();
        //        intResult = (cmd.Parameters["@ReturnVal"].Value == System.DBNull.Value) ? 0 : Convert.ToInt32(cmd.Parameters["@ReturnVal"].Value.ToString());
        //    }
        //}
        return intResult;
    }

    #endregion

    #region UpdateRecord
    /// <summary>
    /// Update the record of the database
    /// </summary>
    /// <param name="storedProcedureName">Stored Procedure Name</param>
    /// <param name="ht">Hashtable of the data to be updated</param>
    /// <returns></returns>
    public static int UpdateRecord(string storedProcedureName, Hashtable ht)
    {
        int intResult = 0;
        //using (SqlConnection conn = DB.NewSqlConnection())
        //{
        //    using (SqlCommand cmd = new SqlCommand(storedProcedureName, conn))
        //    {
        //        cmd.CommandType = CommandType.StoredProcedure;
        //        IDictionaryEnumerator e = ht.GetEnumerator();
        //        while (e.MoveNext())
        //        {
        //            cmd.Parameters.AddWithValue(e.Key.ToString(), e.Value.ToString());
        //        }
        //        conn.Open();
        //        intResult = cmd.ExecuteNonQuery();
        //    }
        //}
        return intResult;
    }

    #endregion

    #region DeleteRecord
    /// <summary>
    /// Delete record from database
    /// </summary>
    /// <param name="storedProcedureName">Stored Procedure Name</param>
    /// <param name="ht">Hashtable containing criteria to delete record from database</param>
    /// <returns></returns>
    public static bool DeleteRecord(string storedProcedureName, Hashtable ht)
    {
        bool status = false;
        //using (SqlConnection conn = DB.NewSqlConnection())
        //{
        //    using (SqlCommand cmd = new SqlCommand(storedProcedureName, conn))
        //    {
        //        cmd.CommandType = CommandType.StoredProcedure;
        //        IDictionaryEnumerator e = ht.GetEnumerator();
        //        while (e.MoveNext())
        //        {
        //            cmd.Parameters.AddWithValue(e.Key.ToString(), e.Value.ToString());
        //        }
        //        conn.Open();
        //        int intResult = cmd.ExecuteNonQuery();
        //        if (Convert.ToBoolean(intResult))
        //        {
        //            status = true;
        //        }
        //        else
        //        {
        //            status = false;
        //        }
        //    }
        //}
        return status;
    }
    
    #endregion

    #region GetDuplicateRecord
    /// <summary>
    /// Returns if the data is duplicate
    /// </summary>
    /// <param name="storedProcedureName">Stored Procedure Name</param>
    /// <param name="ht">Hashtable containing criteria column</param>
    /// <returns></returns>
    public static bool GetDuplicateRecord(string storedProcedureName, Hashtable ht)
    {
        DataTable dt = new DataTable();
        //using (SqlConnection conn = DB.NewSqlConnection())
        //{
        //    using (SqlCommand cmd = new SqlCommand(storedProcedureName, conn))
        //    {
        //        cmd.CommandType = CommandType.StoredProcedure;

        //        IDictionaryEnumerator e = ht.GetEnumerator();
        //        while (e.MoveNext())
        //        {
        //            cmd.Parameters.AddWithValue(e.Key.ToString(), e.Value.ToString());
        //        }
        //        conn.Open();
        //        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
        //        {
        //            da.Fill(dt);
        //        }
        //        return (dt.Rows.Count > 0) ? true : false;
        //    }
        //}
        return true;
    }

    #endregion

    #region SendEmail
    /// <summary>
    /// Send Email from the site
    /// </summary>
    /// <param name="strFrom">From Address</param>
    /// <param name="strTo">To Address</param>
    /// <param name="strCC">CC Address</param>
    /// <param name="strSubject">Subject of email</param>
    /// <param name="strBody">Body of email</param>
    public static void SendEmail(string strFromName, string strFromEmail, string strToName,string strToEmail, string strCCName,string strCCEmail, string strSubject, string strBody)
    {
        try
        {
            System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
            mail.From = new MailAddress(strFromEmail,strFromName);
            mail.To.Add(new MailAddress(strToEmail,strToName));
            if (strCCName.Length != 0 || strFromEmail.Length !=0)
            {
                mail.CC.Add(new MailAddress(strCCEmail,strCCName));
            }
            mail.Subject = strSubject;
            mail.Body = strBody;
            mail.IsBodyHtml = true;
            mail.Priority = MailPriority.Normal;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = ConfigurationManager.AppSettings["SMTP"];
            smtp.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["FROMEMAIL"], ConfigurationManager.AppSettings["FROMPWD"]);
            smtp.EnableSsl = true;
            smtp.Send(mail);
        }
        catch (Exception)
        {
        }
    }
	#endregion

    #region GetRandomString
    /// <summary>
    /// Generated random string
    /// </summary>
    /// <param name="strlength">Length of the string to be generated</param>
    /// <returns></returns>
    public static string GetRandomString(int strlength)
    {
        Random rnd = new Random();
        string strRandom = "";
        string strNextRandom = "";
        int strNextNumber = 0;
        for (int i = 0; i < strlength; i++)
        {
            strNextNumber = rnd.Next(65, 90);
            //Get next number using random function between 65 to 90.
            strNextRandom = new string((Char)strNextNumber, 1);
            //convert to ascii value to char          
            strRandom += strNextRandom;
        }
        return strRandom.ToLower().ToString();
    }
    
    #endregion

    #region ReplaceBetweenSpecialCharacter
    /// <summary>
    /// Replaces the string based on criteria or special character
    /// </summary>
    /// <param name="inputString">Original string</param>
    /// <param name="beginChar">Initial Character from where string to be replaced</param>
    /// <param name="endChar">Terminating Character from the string to be replaced</param>
    /// <param name="replacingString">Replacing string within characters</param>
    /// <returns></returns>
    public static string ReplaceBetweenSpecialCharacter(string inputString, char beginChar, char endChar, string replacingString)
    {
        Regex regex = new Regex(string.Format("\\{0}.*?\\{1}", beginChar, endChar));
        return regex.Replace(inputString, replacingString);
    } 
    #endregion

    #region ReplaceString
    /// <summary>
    /// Replace the string with supplied string
    /// </summary>
    /// <param name="strInput">Original String</param>
    /// <param name="strReplaced">String to be replaced</param>
    /// <param name="strReplacing">String replacing original string</param>
    /// <returns></returns>
    public static string ReplaceString(string strInput, string strReplaced, string strReplacing)
    {
        return Regex.Replace(strInput, strReplaced, strReplacing);
    } 
    #endregion
    
    #region GenerateEmailFromDatabase
    /// <summary>
    /// Get the email template from database
    /// </summary>
    /// <param name="htCriteria">Provides the hashtable criteria for parameter of stored procedure</param>
    /// <param name="htReplace">Provides the replacing hashtable</param>
    /// <returns></returns>
    public static string GetEmailTemplateFromDatabase(Hashtable htCriteria, Hashtable htReplace)
    {
        SqlParameter[] arrParam = new SqlParameter[htCriteria.Count];
        int i = 0;
        foreach (string key in htCriteria.Keys)
        {
            arrParam[i] = new SqlParameter("@" + key + "", htCriteria[key]);
            i++;
        }
        DataTable dt = GeneralFunction.ExecuteDataTable("sp_SCS_GetEmailTemplateByName", arrParam);
        string emailDescription = dt.Rows[0]["EmailTemplateDescription"].ToString();

        foreach (string key in htReplace.Keys)
        {
            emailDescription = GeneralFunction.ReplaceString(emailDescription, key.ToString(), htReplace[key].ToString());
        }
        return emailDescription;
    } 
    #endregion
}
